package com.lx.bizimpl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lx.biz.IDept;
import com.lx.domain.Dept;
@Transactional
@Service("iDeptimpl")
public class IDeptimpl implements IDept {
	
	@Autowired
	private SessionFactory sessionFactory;  

	public void setSessionFactory(SessionFactory sessionFactory) {  
	    this.sessionFactory = sessionFactory;  
	}  
	
	@Override
	public List<Dept> geteDepts(String deptName) {
		if (deptName ==null|| deptName.equals("") ) {
			 String hql = "from Dept ORDER BY ord ASC";
			 Query query = sessionFactory.getCurrentSession().createQuery(hql);
				@SuppressWarnings("unchecked")
				List<Dept> list = query.list();
	            return list; 
		}	else {
			
			String hql = "from Dept where deptName like ? ";
			 Query query = sessionFactory.getCurrentSession().createQuery(hql);
			 query.setString(0, "%"+deptName+"%");
				@SuppressWarnings("unchecked")
				List<Dept> list = query.list();
	            return list; 
		}	  
		   
		  
	
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED , rollbackFor = java.lang.Exception.class)
	public void update(Dept dept) {
		Session session= sessionFactory.getCurrentSession();
		if (dept.getId()==null||dept.getId()==0) {
			Date nowDate = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				String datesString = df.format(nowDate);
				Date date = df.parse(datesString);
				dept.setCreatTime(date);
			} catch (Exception e) {
				
			}
			
		}
		session.saveOrUpdate(dept);
		/*session.beginTransaction().commit();*/
	}

	@Override
	public void delete(String id) {
		  if (id != null && !id.equals("") ) {
			 Integer id1=Integer.parseInt(id);
			 String hql = "delete from Dept where id = ?" ;
			 Query query = sessionFactory.getCurrentSession().createQuery(hql);
			 query.setInteger(0, id1);
		}

	}

	@Override
	public Dept findDept(String id) {
		Dept dept =null ;
		if (id != null && !id.equals("") ) {
		Integer id1=Integer.parseInt(id);
		String hql = "from Dept where id = ?" ;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setInteger(0, id1);
		dept = (Dept)query.uniqueResult() ;
		}
		return  dept;
	}

	@Override
	@Transactional
	public void insert(Dept dept) {
		sessionFactory.getCurrentSession().saveOrUpdate(dept);
	}

}
